#include "TextureManager.hpp"
#include "TextureObject.hpp"
#include <iostream>

//! Setting values for static variables.
TextureManager*    TextureManager::m_instance = 0;

//! GetInstance method returns pointer to TextureManager instance
//! and ensures that only one such instance exists.
TextureManager* TextureManager::GetInstance()
{
	if( !m_instance )
	{
		m_instance = new TextureManager;
	}

	return m_instance;
}

TextureManager::TextureManager()
{
}

bool TextureManager::IsAlreadyLoaded(const std::string &fileName)
{
	std::map<string, void* >::const_iterator filePosition;

	filePosition = m_texMap.find( fileName );

	if( filePosition == m_texMap.end() )
		return false;

	return true;
}

bool TextureManager::LoadTexture( std::string fileName )
{
	if( !IsAlreadyLoaded( fileName ) )
	{
		//! If texture specified by filename isn't already in memory than load it.
		TextureObject* newTexture = new TextureObject( fileName );

		//if( !newTexture->HaveBitmapData() )
		//{
		//	cout << "TextureObject(): error in loading " << fileName << "\n";
		//	return false;
		//}

		m_texMap.insert( std::make_pair( fileName, (void*)newTexture ) );
		newTexture->IncreaseCounter();

		return true;
	}
	else
	{
		//! If texture is already loaded increase it's reference counter.
		map<string, void*>::const_iterator ptr = m_texMap.find( fileName );
		TextureObject* tex = (TextureObject*)ptr->second;
		tex->IncreaseCounter();

		return true;
	}
}

bool TextureManager::UnloadTexture(std::string fileName)
{
	map<string, void*>::const_iterator ptr = m_texMap.find( fileName );
	TextureObject* tex = (TextureObject*)ptr->second;

	//! If there are at least two references to this texture - decrease counter.
	if( tex->GetCounter() > 1 )
		tex->DecreaseCounter();
	else
	{
	//! If this is last reference to texture - delete TextureObject and erase this texture from map.
		delete tex;
		m_texMap[ fileName ] = NULL;

		m_texMap.erase( ptr );
	}

	return true;
}

void* TextureManager::GetTexture(std::string fileName)
{
	return (m_texMap.find( fileName ))->second;
}